<template>
	<view class="container">
		<view class="recharge-mode">
			<view class="left">
				充值方式
			</view>
			<view class="right">
				<text>支付宝</text>
				<uni-icons type="right" ></uni-icons>
			</view>
		</view>
		<view class="recharge-amount">
			<view class="up">
				充值金额
			</view>
			<view class="down">
				<!--自定义金额-->
				<view 
					class="custom-amount" 
					:class="{ selected: 0 === selectedDomId }" 
					@tap="changeCurrDomId(0)"
				>
					<view class="custom-left" >
						自定义充值
					</view>
					<view class="custom-right">
						<input type="number" v-model="inputAmount" @input="onInput" placeholder="请输入金额" placeholder-style="font-size: 30rpx;"/>
					</view>
				</view>
				<!--可选金额-->
				<view class="choose-amount">
					<view 
					class="chooseable-item" 
					:class="{ selected: amt === selectedDomId }" 
					v-for="(amt, idx) in chooseableAmounts" 
					:key="idx" 
					@tap="changeCurrDomId(amt)">
						{{ amt }}元
					</view>
				</view>
			</view>
		</view>
		
		<!-- web端支付宝H5支付（隐藏） -->
		<view v-if="h5PayForm" id="alipay-h5-form" v-html="h5PayForm"></view>
		
		<view class="recharge-btn primary-btn" @tap="handleRecharge">
			￥{{ btnAmount }} 立即充值
		</view>
	</view>
</template>

<script setup>
import { nextTick, ref, watch } from 'vue'
import { recharge, checkRecharge } from '@/api/recharge.js'
import { useUserStore } from '@/stores/userStore.js'
import { formatAmount } from '@/utils/amountUtil.js'
import { rechargeTypeEnum } from '@/utils/enums.js'

const driver = useUserStore()

const chooseableAmounts = ref([ 30, 50, 100, 150, 200, 300 ])

const selectedDomId = ref(30)

const inputAmount = ref(30)

const btnAmount = ref(30)

//H5端支付相关变量
const h5PayForm = ref('')

function changeCurrDomId (domId) {
	selectedDomId.value = domId
	if (domId === 0) {
		btnAmount.value = inputAmount.value
	} else {
		btnAmount.value = domId
	}
}

watch(inputAmount, (nv, ov) => {
	btnAmount.value = nv
})

function onInput (e) {
	// console.log(e.detail.value)
	const amountStrs = (e.detail.value+ '').split('.')
	if (amountStrs.length === 2 && amountStrs[1].length > 2) {
		inputAmount.value = (e.detail.value * 1).toFixed(2)
	}
}

function handleRecharge () {
	if (!btnAmount.value) {
		uni.showToast({
			icon: 'none',
			title: '请输入金额！'
		})
		return
	} else if (btnAmount.value < 30) {
		uni.showToast({
			icon: 'none',
			title: '最少需要充值30元！'
		})
		return
	} else if (btnAmount.value > 10000) {
		uni.showToast({
			icon: 'none',
			title: '最多充值10000元！'
		})
		return
	}
	checkRecharge().then(res => {
		// console.log(res.data)
		if (res.data === null || res.data.length === 0) {
			doRecharge()
		} else {
			uni.showModal({
				title: '提示',
				content: `您有一单未支付的充值记录，确认继续充值吗？`,
				success: (res) => {
					if (res.confirm) {
						doRecharge()
					}
				}
			})
		}
	})
}

function doRecharge () {
	// #ifdef APP-PLUS
	recharge({
		amount: btnAmount.value * 100,
		payChannel: 1,
		rechargeType: rechargeTypeEnum.COMMON.value
	}).then(res => {
		uni.requestPayment({
			provider: 'alipay',
			orderInfo: res.data,
			success: (res) => {
				setTimeout(() => {
					driver.refreshCurrentDriver()
				}, 200)
				uni.showToast({
					icon: 'none',
					title: '支付成功',
					success: () => {
						uni.navigateBack()
					}
				})
			},
			fail: (err) => {
				uni.showToast({
					icon: 'none',
					title: '支付失败'
				})
			}
		})
	})
	// #endif
	
	//当不在app内编译，在web端编译
	// #ifndef APP-PLUS
	recharge({
		amount: btnAmount.value * 100,
		payChannel: 3,
		rechargeType: rechargeTypeEnum.COMMON.value
	}).then(res => {
		console.log('收到后端支付响应:', res.data)
		
		if (!res.data) {
			uni.showToast({
				icon: 'none',
				title: '支付数据为空'
			})
			return
		}
		
		h5PayForm.value = res.data
		
		nextTick(() => {
			const formContainer = document.querySelector('#alipay-h5-form')
			const form = formContainer ? formContainer.querySelector('form') : null;
			if (form) {
				console.log('找到支付表单，准备提交')
				console.log('表单action:', form.action);
				console.log('表单method:', form.method)
				try {
					//直接提交表单（支付宝表单自带提交逻辑，无需额外处理）
					if(typeof form.submit === 'function') {
						form.submit();
					} else {
					//兼容方案：创建隐藏提交按钮并触发点击
						const submitBtn = document.createElement('input')
						submitBtn.type = 'submit'
						submitBtn.style.display = 'none'
						form.appendChild(submitBtn)
						submitBtn.click()
					}
				}catch{
					console.error('未找到支付表单')
					uni.showToast({
						icon: 'none',
						title: '表单解析失败'
					})
				}
			}
		})
	}).catch(err => {
		console.error('支付请求失败:', err)
		uni.showToast({
			icon: 'none',
			title: 'H5支付请求失败'
		})
	})
	return
	// #endif
}

</script>
<style lang="scss" scoped>
view {
	box-sizing: border-box;
}

.container {
	width: 100vw;
	height: 100vh;
	background-color: #f8f8f8;
	padding: 30rpx;
	.recharge-mode {
		display: flex;
		align-items: center;
		justify-content: space-between;
		// background-color: red;
		padding: 30rpx 0;
		border-bottom: 1rpx solid #ddd;
		border-top: 1rpx solid #ddd;
		.left {
			
		}
		.right {
			display: flex;
			align-items: center;
		}
	}
	.recharge-amount {
		padding: 20rpx 0;
		border-bottom: 1rpx solid #ddd;
		.up {
			
		}
		.down {
			margin-top: 20rpx;
			.custom-amount {
				display: flex;
				align-items: center;
				justify-content: space-between;
				border-radius: 20rpx;
				border: 2rpx solid #ccc;
				padding: 20rpx 60rpx;
				.custom-left {
					font-size: 26rpx;
				}
				.custom-right {
					flex: 1;
					input {
						text-align: center;
						font-size: 45rpx;
						font-weight: 600;
					}
				}
			}
			.selected {
				border-color: $uni-color-primary;
			}
			.choose-amount {
				margin-top: 20rpx;
			    display: grid;
			    grid-template-columns: repeat(3, 1fr); /* 三列 */
			    grid-template-rows: repeat(2, 1fr);    /* 两行 */
			    gap: 20rpx;                            /* 网格项之间的间距 */
				.chooseable-item {
					padding: 30rpx 0;
					border-radius: 20rpx;
					border: 2rpx solid #ccc;
					display: flex;
					align-items: center;
					justify-content: center;
				}
				.selected {
					border-color: $uni-color-primary;
				}
			}
		}
	}
	/* 隐藏H5支付表单容器（仅用于提交，默认隐藏） */
	.h5-pay-container {
		display: none;
		position: fixed;
		top: -9999rpx;
		left: -9999rpx;
	}
	.recharge-btn {
		margin-top: 20rpx;
		padding: 20rpx 0;
		text-align: center;
		color: #fff;
		border-radius: 8rpx;
		font-size: 32rpx;
		transition: all 0.2s ease;
	}
}

</style>